<template>
  <div>
    <form class="am-search" action="/">
      <van-search
        v-model="name"
        show-action
        @clear="name = ''"
        @input="onChange"
        @cancel="onCancel"
        @click="isClick = false"
        @blur="isClick = true"
        :input-align="isClick ? 'center' : 'left'"
        placeholder="请输入小区或地址"
      />
    </form>
    <van-cell-group v-if="CommunityList.length">
      <van-cell
        v-for="(item, index) in CommunityList"
        :key="index"
        :title="
          item.cityName + item.areaName + item.streetName + item.communityName
        "
        @click="SetCommunityName(item)"
      />
    </van-cell-group>
  </div>
</template>
<script>
import { getCommunity } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'search',
  components: {},
  props: {},
  data() {
    return {
      name: '',
      id: this.$store.state.cityValue,
      // 防抖 定时器
      Timer: null,
      // 社区信息列表
      CommunityList: [],
      // 让提示文字居中效果
      isClick: true
    }
  },
  computed: {},
  watch: {},
  created() {},
  methods: {
    ...mapMutations(['SET_COMMUNITY']),
    //  取消事件
    onCancel() {
      this.value = ''
      this.$router.back()
    },

    // 输入框变化发起请求
    onChange() {
      if (this.name === '') return
      //  手写防抖
      if (this.Timer) clearTimeout(this.Timer)
      this.Timer = setTimeout(async () => {
        const { data: res } = await getCommunity({
          id: this.id,
          name: this.name
        })
        if (res.body.length === 0) {
          return this.$toast.fail('查询不到该社区名称！')
        }
        this.CommunityList = res.body
      }, 2000)
    },
    // 点击cell单元格跳转
    SetCommunityName(item) {
      this.SET_COMMUNITY(item)
      this.$router.back()
    }
  }
}
</script>

<style scoped lang="less">
.am-search {
  background-color: #f6f5f6 !important;
}
:deep(.van-search) {
  height: 88px !important;
  background-color: unset;
  .van-search__content {
    background-color: #fff;
    height: 56px !important;
    line-height: 56px !important;
    display: flex;
    align-items: center;
    border-radius: 5px;
    .van-cell {
      padding: 0px;
    }
  }
}
</style>
